package com.gxa.learning.pc.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.common.JsonResult;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.ProjectApply;
import com.gxa.learning.core.pojo.User;
import com.gxa.learning.core.pojo.UserRole;
import com.gxa.learning.core.util.MD5Util;
import com.gxa.learning.core.util.StringUtil;
import com.gxa.learning.pc.service.ProjectApplyService;
import com.gxa.learning.pc.service.ProjectService;
import com.gxa.learning.pc.service.UserRoleService;
import com.gxa.learning.pc.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @Author ChenJ
 * @date 2021/12/06 14:56
 **/
@RestController
@RequestMapping("/student")
@Api(value = "StudentController", tags = "操作学员的接口")
public class StudentController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private ProjectApplyService projectApplyService;

    @Autowired
    private ProjectService projectService;

    private static String SALT = "chenj";

    @PostMapping("/insert")
    @ApiOperation("添加学员的接口")
    @ApiImplicitParam(name = "user", value = "user", paramType = "body", dataType = "User", dataTypeClass = User.class)
    @Transactional
    public Map<String, Object> insert(@RequestBody User user) throws BusinessException {

        // 先进行数据校验
        if (user == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        if (!StringUtil.isEmail(user.getEmail())) {
            throw new BusinessException(ExceptionCode.WRONG_EMAIL);
        }
        if (!StringUtil.isPhoneNumber(user.getPhone())) {
            throw new BusinessException(ExceptionCode.WRONG_PHONE);
        }

        User findUser = new User();
        findUser.setPhone(user.getPhone());
        // 根据手机号查找用户,如果存在则抛出异常
        List<User> select = userService.select(findUser);
        System.out.println("select:" + select);
        if (select.size() != 0) {
            throw new BusinessException(ExceptionCode.HAS_PHONE);
        }
        user.setStatus(1);
        String phone = user.getPhone();
        String substring = phone.substring(5);
        user.setPassword(MD5Util.encode(substring + SALT));
        user.setSalt(SALT);
        // 添加用户操作
        User insert = userService.insert(user);

        UserRole userRole = new UserRole();
        // 添加用户编号用于关联
        userRole.setUId(insert.getId());
        // 设置成学院角色
        userRole.setRId(3L);
        // 将关联关系添加至关联表
        userRoleService.insert(userRole);
        if (insert == null) {
            throw new BusinessException(ExceptionCode.FAILED_OPTION);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/getList")
    @ApiOperation("获取学员列表的接口（包含模糊查询）")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
    public Map<String, Object> getList(@RequestBody Map<String, Object> map) {
        if (map.get("page") != null) {
            PageHelper.startPage(Integer.valueOf(map.get("page").toString()), Integer.valueOf(map.get("size").toString()));
        }

        JsonResult jsonResult = new JsonResult();
        System.out.println("id:" + map.get("id") + "--------------------------------");
        if (map.get("id") != null) {
            System.out.println("传来id,进这里面来了");
            Map<String, Object> user = userService.getOne(Long.valueOf(map.get("id").toString()));
            jsonResult.setData(user);
        } else {
            List<Map<String, Object>> list = null;
            Long total = null;
            // 先查询获取所有的学员
            list = userService.getList(map);
            System.out.println("list:" + list);
            // 遍历添加学员添加的培训
            for (Map<String, Object> stringObjectMap : list) {
                ProjectApply projectApply = new ProjectApply();
                projectApply.setUserId(Long.valueOf(stringObjectMap.get("id").toString()));
                List<ProjectApply> select = projectApplyService.select(projectApply);
                // 在数据上添加学员参加的培训总数
                stringObjectMap.put("projectNum", select.size());
            }

            System.out.println("list1:" + list);
            // 如果前段传来了页码则进行分页
            if (map.get("page") != null) {
                PageInfo<Map<String, Object>> of = PageInfo.of(list);
                list = of.getList();
                total = of.getTotal();
                // 返回前段的数据加上总数
                jsonResult.put("count", total);
            }
            // 添加分页的数据
            jsonResult.setData(list);
        }
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");

        return jsonResult.getDataMap();
    }

    @PostMapping("/getProject")
    @ApiOperation("获取学员参加的培训列表的接口")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
    public Map<String, Object> getProject(@RequestBody Map<String, Object> map) throws BusinessException {

        if (map == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        if (map.get("id") == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> userProject = projectService.getUserProject(map);
        for (Map<String, Object> stringObjectMap : userProject) {
            Object endTime = stringObjectMap.get("project_endTime");
            stringObjectMap.put("project_endTime", simpleDateFormat.format(endTime));
        }

        JsonResult jsonResult = new JsonResult();

        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        jsonResult.setData(userProject);

        return jsonResult.getDataMap();
    }


}
